package actionbean;

import javax.servlet.http.HttpSession;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.validation.LocalizableError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidationErrors;
import controller.StudentCtrl;

public class LoginActionBean extends BaseActionBean {

	public static final String ADMIN_USERID = "admin";
	private static final String ADMIN_PASSWORD = "3a6a4a8a";

	private StudentCtrl studentCtrl = new StudentCtrl();

	@Validate(required = true)
	private String userId;

	@Validate(required = true)
	private String password;

	private String targetUrl;

	public void setTargetUrl(String targetUrl) {
		this.targetUrl = targetUrl;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	private boolean isAdmin() {
		return userId.equals(ADMIN_USERID);
	}

	private boolean authenticateAdmin() {
		return userId.equals(ADMIN_USERID) && password.equals(ADMIN_PASSWORD);
	}

	@DefaultHandler
	public Resolution authenticateUser() {

		boolean isUserAuthorized = false;

		if (isAdmin()) {
			isUserAuthorized = authenticateAdmin();
		} else {
			isUserAuthorized = studentCtrl
					.authenticateStudent(userId, password);
		}

		if (isUserAuthorized) {
			// set session
			HttpSession session = getContext().getRequest().getSession();
			session.setAttribute("loggedInUserId", userId);

			// redirect to another page after successful login
			return new RedirectResolution(getTargetUrl());
		} else {
			// return back to login page with an error
			ValidationErrors errors = new ValidationErrors();
			errors.addGlobalError(new LocalizableError("loggin.failed"));
			getContext().setValidationErrors(errors);

			return getContext().getSourcePageResolution();
		}

	}

	private String getTargetUrl() {

		if (targetUrl == null || targetUrl.isEmpty()) {
			if (isAdmin()) {
				targetUrl = DEFAULT_ADMIN_URI;
			} else {
				targetUrl = DEFAULT_STUDENT_URI;
			}
		}

		return targetUrl;
	}

}
